<template>
  <basic-container :btnFlag="true">
    <div class="card-border">
      <card-header :header-data="headerData"></card-header>

      <div class="form-group">
        <span class="form-label">规划名称:</span>
        <input type="text"
               name="key"
               v-model="selectedOptions.titleLike"
               id="searchInput"
               ref="searchInput"
               placeholder="请输入规划名称"
               style="width: 500px;"
               @keyup.enter="searchSubmit()" />
        <div class="form-submit">
          <el-button type="warning"
                     size="small"
                     @click.stop="searchSubmit()">查询</el-button>

          <el-button type="warning"
                     size="small"
                     @click.stop="exportExcel()">
            导出
          </el-button>
          <el-button type="info"
                     size="small"
                     @click.stop="searchReset()">重置</el-button>
        </div>
      </div>
      <transition name="fade"
                  @before-leave="searchTransition()"
                  @after-enter="searchTransition()">
        <div v-if="showAll">
          <div :class="{showAll:true,active:showAll}">
            <el-divider></el-divider>
            <avue-search ref="search"
                         :option="option"
                         v-model="selectedOptions"
                         @change="handleChange"></avue-search>
          </div>
        </div>
      </transition>
      <div class="search-collapse">
        <div class="collapse-title"
             :class="{active:showAll}"
             @click="showAll = !showAll">
          <img v-if="!showAll"
               :src="`${publicPath}img/packdown.png`"
               class="collapse-title-img">
          <p v-if="!showAll"
             class="collapse-title-text">展开搜索条件1</p>
          <img v-if="showAll"
               :src="`${publicPath}img/packUp.png`"
               class="collapse-title-img">
          <p v-if="showAll"
             class="collapse-title-text">收起搜索条件</p>
        </div>
      </div>

      <div style="margin-top: 18px;margin-left: 10px;font-weight: 600;">搜索结果列表</div>

      <div class="card-body">
        <avue-crud :data="resultListData"
                   :option="tableOption"
                   :page="page"
                   :table-loading="tableLoading"
                   @refresh-change="refreshChange"
                   @search-change="searchChange"
                   @on-load="onload"
                   class="avuecrud">
          <template slot-scope="scope"
                    slot="unitName">
            <el-popover placement="top-start"
                        title=""
                        trigger="hover">
              <div class="popover-column">
                <div class="popover-column-cell">
                  <span>科室 :</span>
                </div>
                <div class="popover-column-cell">
                  <span>{{scope.row.deptName}}</span>
                </div>
              </div>
              <div class="popover-column">
                <div class="popover-column-cell">
                  <span>联系人 :</span>
                </div>
                <div class="popover-column-cell">
                  <span>{{scope.row.contactName}}</span>
                </div>
              </div>
              <div class="popover-column">
                <div class="popover-column-cell">
                  <span>联系方式 :</span>
                </div>
                <div class="popover-column-cell">
                  <span>{{scope.row.contactNumber}}</span>
                </div>
              </div>
              <p slot="reference">{{scope.row.unitName}}</p>
            </el-popover>
          </template>
        </avue-crud>
      </div>
    </div>
  </basic-container>
</template>
<script>
import { PROJECT_DIC } from "@/const/dict";
import { resultList } from "@/api/planning/result";
import { getAreaByType } from "@/api/system";
import store from "@/store"; // progress bar style
import {mapGetters} from "vuex";

export default {
  name: "listConlumn",
  computed: {
    ...mapGetters([
      "deptInfo"
    ])
  },
  mounted () {
    this.putResultListThisYear()
  },
  created () {
    window.resultDetail = this.resultDetail;
    this.getSelectedOptionsHistory();
  },
  data () {
    const getYearDic = _ => {
      return [
        {
          label: "全部",
          value: "-1"
        }
      ].concat(PROJECT_DIC.YEAR);
    };
    const getApplyForCategoryDic = _ => {
      return [
        {
          label: "全部",
          value: "-1"
        }
      ].concat(PROJECT_DIC.CATEGORY);
    };
    const getPlanningRankDic = _ => {
      return [
        {
          label: "全部",
          value: "-1"
        }
      ].concat(PROJECT_DIC.PLANNING_RANK);
    };
    const getLevelDic = _ => {
      return [
        {
          label: "全部",
          value: "-1"
        }
      ].concat(PROJECT_DIC.PLANNING_LEVEL);
    };

    return {
      headerData: {
        title: "规划立项目录"
      },
      state: "0,1,2,3,4,5", //状态
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 10 // 每页显示多少条
      },
      tableLoading: false,
      resultListData: [],
      tableOption: {
        page: true,
        menu: false,
        addBtn: false,
        editBtn: false,
        addRowBtn: false,
        indexLabel: "序号",
        index: true,
        indexWidth: 70,
        cellBtn: false,
        delBtn: false,
        columnBtn: false,
        refreshBtn: false,
        filterBtn: false,
        searchBtn: false,
        keyId: "id",
        column: [
          {
            label: "规划编码",
            prop: "pmuc",
            width: 200,
            cell: true
          },
          {
            label: "规划名称",
            prop: "title",
            cell: true,
            formatter: function (row, value, label, column) {
              return (
                '<a style="cursor: pointer;" onclick="resultDetail(\'' + row.achievementId + '\',\'' + row.pmuc + '\')">' +

                value +
                "</a>"
              );
            }
          },
          {
            label: "地区",
            prop: "areaName",
            width: 100,
            cell: true
          },
          {
            label: "年份",
            prop: "year",
            width: 60,
            cell: true
          },
          {
            label: "申报单位",
            prop: "unitName",
            width: 100,
            slot: true,
            cell: true
          }, {
            label: "申报时间",
            prop: "createTime",
            width: 100,
            cell: true,
            formatter: function (row, value, label, column) {
              if (row.createTime != null) {
                let data = row.createTime.split(' ');
                return data[0];
              }
            }
          },
          {
            label: "规划类型",
            prop: "category",
            type: "select",
            dicData: PROJECT_DIC.CATEGORY,
            cell: true,
            width: 100,
            formatter: function (row, value, label, column) {
              if (row.category == 'B') {
                switch (row.planningRank) {
                  case 'A': return '重点专项规划'; break;
                  case 'B': return '一般专项规划'; break;
                  case 'C': return '备案专项规划'; break;
                }
              } else {
                switch (row.category) {
                  case 'A': return '发展规划'; break;
                  case 'C': return '区域规划'; break;
                  case 'D': return '空间规划'; break;
                }
              }
            }
          }
        ]
      },
      option: {
        column: [
          {
            label: "年份",
            prop: "year",
            multiple: false,
            dicData: getYearDic()
          },
          {
            label: "规划类型",
            prop: "categorys",
            multiple: false,
            dicData: getApplyForCategoryDic()
          },
          {
            label: "发布等级",
            prop: "planningRanks",
            multiple: false,
            dicData: getPlanningRankDic()
          },
          {
            label: "发布层级",
            prop: "planningLevels",
            multiple: false,
            dicData: getLevelDic()
          },
          {
            label: "市级",
            prop: "city",
            multiple: false,
            dicData: [{
              label: '全部',
              value: '-1',
            }],
          },
          {
            label: "区县",
            prop: "county",
            multiple: false,
            dicData: [{
              label: '全部',
              value: '-1',
            }],
          },
        ]
      },
      selectedOptions: {
        categorys: "-1",
        planningRanks: "-1",
        planningLevels: "-1",
        city: "-1",
        county: "-1",
        year: "-1",
        titleLike: ""
      },
      resetSelectedOptions: {
        categorys: "-1",
        planningRanks: "-1",
        planningLevels: "-1",
        city: "-1",
        areCode: "-1",
        county: "-1",
        year: "-1",
        titleLike: ""
      },
      selectedOptionsHistory: {
        categorys: "-1",
        planningRanks: "-1",
        planningLevels: "-1",
        city: "-1",
        county: "-1",
        year: "-1",
        titleLike: ""
      },
      showAll: false,
      publicPath: process.env.BASE_URL,
      dictObj: {
        label: "全部",
        value: "-1"
      },
      areaDictTemp: {},
    };
  },
  watch: {
    //市级的监听
    'selectedOptions.city' (val) {
      this.selectedOptions.county = '-1';
      //将区县置空
      for (let column of this.option.column) {
        if (column.prop == "county") {
          column.dicData = [{ label: '全部', value: '-1' }]
        }
      }
      let cityAreaCode = val.substring(0, 4);
      this.getAreaDictCounty(cityAreaCode);
    }
  },
  methods: {
    async exportExcel () {
      let a = this.filterFormData(this.selectedOptions);

      let str = '';

      for (let li of Object.keys(a)) {
        str = str + '&' + li + '=' + a[li];
      }


      let url = '/planning/achievement/catalog/excel?access_token=' + store.getters.access_token + '&states='
        + this.state + '&current=' + this.page.currentPage + '&sources=1' + str;
      // '&area=' + (a.area ? a.area : '') + '&areaCodeLike=' + (a.areaCodeLike ? a.areaCodeLike : '') +
      // '&categorys=' + (a.categorys ? a.categorys : '') +
      // '&planningLevels=' + (a.planningLevels ? a.planningLevels : '') +
      // '&planningRanks=' + (a.planningRanks ? a.planningRanks : '') +
      // '&titleLike=' + (a.titleLike ? a.titleLike : '') +
      // '&year=' + (a.year ? a.year : '');
      let link = document.createElement("a");
      link.style.display = "none";
      link.href = url;
      // link.href='blob:'+link.href
      // link.setAttribute("download", "立项目录");
      document.body.appendChild(link);
      link.click();

    },
    searchTransition () {
      if (this.showAll) {
        if (Object.keys(this.areaDictTemp).length == 0) {
          this.getAreaDictCity();
        } else {
          this.$refs.search.DIC = this.areaDictTemp
        }
      } else {
        if (this.$refs.search != null && this.$refs.search.DIC != null) {
          this.areaDictTemp = this.$refs.search.DIC;
        }
      }
    },
    onload (page) {
      this.page = Object.assign(this.page, page);
      this.getResultList();
    },
    getResultList () {
      let page = this.page;
      this.tableLoading = true;
      sessionStorage.setItem(
        "selectedOptionsHistory.categorys",
        this.selectedOptions.categorys
      );
      sessionStorage.setItem(
        "selectedOptionsHistory.planningRanks",
        this.selectedOptions.planningRanks
      );
      sessionStorage.setItem(
        "selectedOptionsHistory.planningLevels",
        this.selectedOptions.planningLevels
      );
      sessionStorage.setItem(
        "selectedOptionsHistory.city",
        this.selectedOptions.city
      );
      sessionStorage.setItem(
        "selectedOptionsHistory.county",
        this.selectedOptions.county
      );
      sessionStorage.setItem(
        "selectedOptionsHistory.year",
        this.selectedOptions.year
      );
      sessionStorage.setItem(
        "selectedOptionsHistory.titleLike",
        this.selectedOptions.titleLike
      );
      resultList(
        Object.assign(
          {
            current: page.currentPage,
            size: page.pageSize,
            states: this.state,
            sources: 1,
            ascs: 'area_code,pmuc'
          },
          this.filterFormData(this.selectedOptions)
        )
      ).then(response => {
        this.resultListData = response.data.data.records;
        this.page.total = response.data.data.total;
        this.tableLoading = false;
      });
    },
    refreshChange () {
      this.getResultList();
    },
    // 搜索
    searchChange (params) {
      this.selectedOptions = Object.assign(this.selectedOptions, this.dealSearchParam(params));
      this.getResultList();
    },
    // 处理搜索过滤
    dealSearchParam (params) {
      if (params.title) {
        params.titleLike = params.title;
        params.title = "";
      }
      if (params.category) {
        params.categorys = params.category;
        params.category = "";
      }
      return params;
    },
    // 成果详情跳转
    resultDetail (achievementId, pmuc) {
      let src = `/planning/achievement/detail?id=${achievementId}&pmuc=${pmuc}`;
      this.$router.push({
        path: src
      });
    },
    searchSubmit () {
      if (
        this.selectedOptions.county != -1 &&
        this.selectedOptions.county != ""
      ) {
        this.selectedOptions.areaCodeLike = this.selectedOptions.county;
      } else {
        this.selectedOptions.areaCodeLike = this.selectedOptions.city;
      }
      this.selectedOptions.areaCodeLike = this.selectedOptions.areaCodeLike.substring(
        0,
        6
      );
      this.page = {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 10 // 每页显示多少条
      };
      this.getResultList();
    },
    searchReset () {
      this.selectedOptions = Object.assign({},this.resetSelectedOptions);
      this.getResultList();
    },
    handleChange (form) {
    },
    getAreaDictCity () {
      let provinceCode = this.deptInfo.areaCode.substring(0, 2);
      getAreaByType(Object.assign({
        current: 1,
        size: -1,
        valueLike: provinceCode,
        type: "area_code_city"
      })).then(response => {
        let records = response.data.data.records;
        let cityList = [];
        cityList.push(this.dictObj);
        for (let item in records) {
          let dictObj = {
            label: records[item].label,
            value: records[item].value
          };
          cityList.push(dictObj)
        }
        this.$refs.search.DIC['city'] = cityList;
      })
    },
    getAreaDictCounty (areaCode) {
      getAreaByType(Object.assign({
        current: 1,
        size: -1,
        valueLike: areaCode,
        type: "area_code_county",
      })).then(response => {
        let records = response.data.data.records;
        let countyList = [];
        countyList.push(this.dictObj);
        for (let item in records) {
          let dictObj = {
            label: records[item].label,
            value: records[item].value
          };
          countyList.push(dictObj)
        }
        this.$refs.search.DIC['county'] = countyList;
      })
    },
    filterFormData (form) {
      let formMap = {};
      Object.keys(form).forEach(function (name) {
        if (form[name] != -1) {
          formMap[name] = form[name];
        }
      });
      return formMap;
    },
    getSelectedOptionsHistory () {
      if (sessionStorage.getItem("selectedOptionsHistory.categorys") != null) {
        this.selectedOptionsHistory.categorys = sessionStorage.getItem(
          "selectedOptionsHistory.categorys"
        );
      }
      if (
        sessionStorage.getItem("selectedOptionsHistory.planningRanks") != null
      ) {
        this.selectedOptionsHistory.planningRanks = sessionStorage.getItem(
          "selectedOptionsHistory.planningRanks"
        );
      }
      if (
        sessionStorage.getItem("selectedOptionsHistory.planningLevels") != null
      ) {
        this.selectedOptionsHistory.planningLevels = sessionStorage.getItem(
          "selectedOptionsHistory.planningLevels"
        );
      }
      if (sessionStorage.getItem("selectedOptionsHistory.county") != null) {
        this.selectedOptionsHistory.county = sessionStorage.getItem(
          "selectedOptionsHistory.county"
        );
      }
      if (sessionStorage.getItem("selectedOptionsHistory.year") != null) {
        this.selectedOptionsHistory.year = sessionStorage.getItem(
          "selectedOptionsHistory.year"
        );
      }
      if (sessionStorage.getItem("selectedOptionsHistory.city") != null) {
        this.selectedOptionsHistory.city = sessionStorage.getItem(
          "selectedOptionsHistory.city"
        );
      }
      if (sessionStorage.getItem("selectedOptionsHistory.titleLike") != null) {
        this.selectedOptionsHistory.titleLike = sessionStorage.getItem(
          "selectedOptionsHistory.titleLike"
        );
      }

      let selectedOptionsHistory = this.selectedOptionsHistory;
      this.selectedOptions = selectedOptionsHistory;

      if (
        this.selectedOptions.county != -1 &&
        this.selectedOptions.county != ""
      ) {
        this.selectedOptions.areaCodeLike = this.selectedOptions.county;
      } else {
        this.selectedOptions.areaCodeLike = this.selectedOptions.city;
      }
      this.selectedOptions.areaCodeLike = this.selectedOptions.areaCodeLike.substring(
        0,
        6
      );
    },
    async putResultListThisYear(){
      this.selectedOptions.year = await new Date().getFullYear().toString();
      this.getResultList()
    },
  }
}
</script>

<style lang="scss" scoped>
/deep/.el-card {
  .head-title {
    font-size: 1rem;
  }
}

/deep/.el-table {
  a {
    font-size: 1rem;
  }
}
.card-border {
  border: 1px solid #d2d2d2;
}

.card-body {
  padding: 10px;
}

.head-button .el-button {
  padding: 8px 15px;
}

.form-group {
  margin-top: 1rem;
  margin-left: 26px;
}

.form-label {
  font-weight: 600;
  margin-right: 2rem;
}

.form-submit {
  float: right;
  margin-right: 22px;
}

.search-collapse {
  margin-top: 1rem;
}

.collapse-title {
  margin-top: -1rem;
  text-align: center;
  border-top: 1px solid #dedbdb;
  border-bottom: 1px solid #dedbdb;
}

.collapse-title-text {
  color: #4297dc;
  display: inline-block;
  font-size: 15px;
  font-weight: 600;
  margin-left: 0.2rem;
  margin: 10px 0px;
}

.collapse-title-img {
  width: 1.2rem;
  position: relative;
  top: 0.25rem;
}

.showAll {
  padding: 10px;
  height: 0px;
  overflow: hidden;

  .fade-enter-active {
    transition: opacity 0.9s ease-out;
  }

  .fade-leave-active {
    transition: opacity 0s ease-out;
  }

  .fade-enter,
  .fade-leave-to {
    opacity: 0;
  }

  clear: both;
  /*margin-top: 6px;*/
}

.showAll.active {
  height: auto;
  background: #fff;
  min-height: 150px;
}

#searchInput {
  height: 40px;
  border: 1px solid #dadada;
  outline: 0;
  line-height: 40px;
  text-indent: 1rem;
  border-radius: 0.31rem;
}

/deep/ .avue-search__title {
  padding: 0 26px;
  margin-left: -13px;
}

.popover-column {
  display: flex;
  justify-content: space-between;
  border-bottom: 1px solid #dadada;
}
.popover-column-cell {
  margin: 5px 0;
}
/deep/ .avue-search__tags--active {
  color: #fff;
  background-color: #1890ff;
  border-radius: 5px;
  padding: 5px 10px;
}
</style>

